package org.thirdeye.reader.helper;

import java.util.ArrayList;
import java.util.HashMap;

import org.thirdeye.reader.ThirdEye_TextReaderDTO;
import org.thirdeye.reader.constants.ApplicationConstants;

import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;


public class PageReader implements OnUtteranceCompletedListener {
	private int endPage;
	private ThirdEye_TextReaderDTO data;
	private TextToSpeech tts;

	public PageReader(ThirdEye_TextReaderDTO data, TextToSpeech tts) {
		this.data = data;
		this.tts = tts;
	}

	public void read(int startPage, int endPage) {
		data.setCurPage(startPage);
		this.endPage = endPage;
		tts.setOnUtteranceCompletedListener(this);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
				ApplicationConstants.END_OF_LINE);
		int curSentence = data.getCurSentence();
		String sentence = data.getPageSentences().get(curSentence);
		tts.speak(sentence, 0, params);
		Log.d("Speaking", sentence);
	}

	private void loadSentences() {
		int i = 0;
		data.setPageSentences(new ArrayList<String>());
		int curPage = data.getCurPage();
		ArrayList<String> pageSentences = new ArrayList<String>();
		while (i < data.getSentenceCnt()
				&& ((i + (curPage * ApplicationConstants.MAX_SENTENCES)) < data
						.getSentences().length)) {
			pageSentences.add(data.getSentences()[i
					+ (curPage * ApplicationConstants.MAX_SENTENCES)]);
			i++;
		}
		data.setPageSentences(pageSentences);
	}

	@Override
	public void onUtteranceCompleted(String id) {
		Log.d("Entering", "onUtteranceCompleted with id:" + id);
		Log.d("Page", "" + data.getCurPage());
		Log.d("Sentence", "" + data.getCurSentence());
		if (id.equalsIgnoreCase(ApplicationConstants.END_OF_LINE)) {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
					ApplicationConstants.END_OF_LINE);
			data.setCurSentence(data.getCurSentence() + 1);
			if (data.isAction() != ApplicationConstants.STOP) {
				int curSentence = data.getCurSentence();
				if (curSentence < data.getSentenceCnt()
						&& curSentence < data.getPageSentences().size()) {

					tts.speak(data.getPageSentences().get(curSentence), 0,
							params);
					Log.d("Speaking", data.getPageSentences().get(curSentence));
				} else if (data.getCurPage() < endPage) {
					Log.d("Navigating", "Next page");
					data.setCurPage(data.getCurPage() + 1);
					curSentence = 0;
					this.loadSentences();
					tts.speak(data.getPageSentences().get(curSentence), 0,
							params);
					Log.d("Speaking", data.getPageSentences().get(curSentence));
				}
			}
		}

	}
}